#include "odmstransferdialog.h"
#include "ui_odmstransferdialog.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>

ODMSTransferDialog::ODMSTransferDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ODMSTransferDialog)
{
    ui->setupUi(this);
    process = new QProcess;
    lastPath = QApplication::applicationDirPath();

    connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &ODMSTransferDialog::onProcessFinished);
}

void ODMSTransferDialog::setLastPath(QString path)
{
    lastPath = path;
}

QString ODMSTransferDialog::getLastPath()
{
    return lastPath;
}

ODMSTransferDialog::~ODMSTransferDialog()
{
    delete ui;
}

void ODMSTransferDialog::on_toolButton_odmsLog_clicked()
{
    // 新建文件选择对话框
    QFileDialog* fileDialog = new QFileDialog(this);

    fileDialog->setDirectory(lastPath);
    QString path = fileDialog->getOpenFileName(this, QString("选择ODMS日志文件"), NULL, QString("fitsco file(*.fitsco)"));
    if (!path.isEmpty()){
        QFileInfo fi(path);
        ui->lineEdit_odmsLog->setText(path);
        lastPath = fi.absolutePath();
    }

}



void ODMSTransferDialog::on_pushButton_cancel_clicked()
{
    this->close();
}


void ODMSTransferDialog::on_pushButton_confirm_clicked()
{

    // 设置要启动的程序
    process->setProgram(QCoreApplication::applicationDirPath() + "/ODMSConversion.exe");
    qDebug()<<QCoreApplication::applicationDirPath() + "/ODMSConversion.exe" ;

    // 设置要传递的参数
    QStringList arguments;
    // 提取文件名前缀
    int dotIndex = ui->lineEdit_odmsLog->text().lastIndexOf('.');
    QString filePrefix = ui->lineEdit_odmsLog->text().left(dotIndex);
    arguments << ui->lineEdit_odmsLog->text() << filePrefix + ".dat";
    process->setArguments(arguments);

    // 启动进程
    process->start();

    // 等待进程完成
    process->waitForFinished();

}

void ODMSTransferDialog::onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    Q_UNUSED(exitStatus)

    if(exitCode != 0) {
        QMessageBox::warning(this, "错误提示!", "日志转换错误, 请检查.fitsco文件是否损坏！" + process->errorString());
    }
    close();
}


